﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Solidi
{
	/// <summary>
	/// Thread safe
	/// </summary>
	public sealed class CircularDependencyResolver : IDependencyResolver
	{
		private IDependencyResolver _resolver;

		public CircularDependencyResolver(IDependencyResolver resolver)
		{
			if (resolver == null)
			{
				throw new ArgumentNullException("resolver");
			}

			_resolver = resolver;
		}

		public bool TryResolve(object graphId, IDependencyContainer container, IDependencyKey key, out object instance)
		{
			return _resolver.TryResolve(graphId, container, key, out instance);
		}

		public bool TryResolve(IDependencyContainer container, IDependencyKey key, out object instance)
		{
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

			IDependencyResolver resolver = container.Resolver;

			resolver = new RootCircularDependencyResolver(resolver);

			container = new DependencyContainer(container.Registry, resolver, container.Composer, container.Lifetime);

			return _resolver.TryResolve(container, key, out instance);
		}

		public bool TryRelease(IDependencyContainer container, object instance)
		{
			return _resolver.TryRelease(container, instance);
		}
	}
}
